package controller;

import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;
import util.Md5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取用户输入
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 使用MD5加密密码
        String encryptedPassword = Md5Util.getMD5String(password);

        // 使用Service验证用户
        User user = userService.login(username, encryptedPassword);

        if (user != null) {
            // 验证成功，将用户信息存入Session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            session.setAttribute("loginTime", new Date());

            // 重定向到菜单页面
            response.sendRedirect("menu.jsp");
        } else {
            // 验证失败，返回登录页面并显示错误信息
            request.setAttribute("errorMsg", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}